package com.orange.zkcase1;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * Description: 服务端和zookeeper集群创建连接
 */
public class DistributeServer {

    //注意：connectString逗号左右不能有空格，否则连接不上
    private String connectString = "192.168.147.128:2181,192.168.147.129:2181,192.168.147.130:2181";
    //tickTime为2000，initLimit为10
    //LF初次连接时的超时时间应起码大于延迟时间tickTime*initLimit的值否则会因为超时而连接失败。
    private int sessionTimeout = 200000;
    private ZooKeeper zkClient;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        DistributeServer server = new DistributeServer();
        //1.连接zookeeper集群,获取zk连接,创建zk
        server.getConnect();

        //2.注册服务器到zk集群
        server.regist(args[0]);

        //3.启动业务逻辑
        server.business();
    }

    private void business() throws InterruptedException {
        //延时阻塞
        Thread.sleep(Long.MAX_VALUE);
    }

    /**
     * 注册服务器,创建节点
     */
    private void regist(String hostname) throws InterruptedException, KeeperException {
        String create = zkClient.create("/servers/" + hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + " is online");
    }

    /**
     * 连接上zookeeper集群
     */
    private void getConnect() throws IOException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }
}